//
//  WmcHtml5VC.swift
//  YPWatermarkCamera
//
//  Created by yupao_ios_macmini06 on 2022/10/18.
//

import UIKit
import WebKit

// MARK: - 扩展WmcHtml5VC + WmcNavigatorProtocol

extension WmcHtml5VC: WmcNavigatorProtocol {
    static func navigationPaths() -> [WmcNavigatorManager.Path] {
        return [.html5Page]
    }

    static func willMakeNavigationVC(with parms: WmcNavigatorManager.Parms) -> UIViewController {
        var vm = WmcHtml5VM()
        if let viewModel = parms.context as? WmcHtml5VM {
            vm = viewModel
        }
        let vc = WmcHtml5VC(vm)
        vc.hidesBottomBarWhenPushed = true
        return vc
    }
}

// MARK: - 扩展WmcHtml5VC + WmcVMProtocol

extension WmcHtml5VC: WmcVMProtocol {
    typealias VMType = WmcHtml5VM
}

// MARK: - [WmcHtml5VC]

/// 通用h5页面
class WmcHtml5VC: WmcBaseVC {
    // Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()
        // 加载webView数据
        self.title = self.viewModel.path?.title
        let request = self.viewModel.requestBuilder(questionType: self.viewModel.questionType ?? .None)
        self.webView.load(request)
    }

    // Internal

    /// js 回调 原生事件处理代理的名称
    let handlerName: String = "ypNative"

    override func makeUI() {
        self.makeNavView(style: .white, showShadow: false)
        addSubview(webView)
        webView.snp.makeConstraints { make in
            make.top.left.right.bottom.equalToSuperview()
        }
        // 添加 js 事件代理（当前控制器（实现 WKScriptMessageHandler ））
        self.contentController.add(self, name: handlerName)
    }

    // Private

    private lazy var webView: WKWebView = {
        let view = WKWebView()
        // 设置代理
        view.navigationDelegate = self
        return view
    }()

    private lazy var contentController: WKUserContentController = webView.configuration.userContentController
}

extension WmcHtml5VC {
    /// H5 js  事件类型
    enum WmcFeedbackMessageId: String, CaseIterable {
        case back
        case saveQrCode
    }
}

extension WmcHtml5VC {
    /// 保存图片到本地相册
    /// - Parameters:
    ///   - image: image description
    ///   - error: error description
    ///   - contextInfo: contextInfo description
    @objc
    private func saveImage(_ image: UIImage, didFinishSaving error: Error?, contextInfo: AnyObject) {
        if error != nil {
            WmcHudManager.toast("保存失败")
        } else {
            WmcHudManager.toast("保存成功")
        }
    }
}

// MARK: - WKScriptMessageHandler

extension WmcHtml5VC: WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        if let messageBody = message.body as? [String: Any],
           let funcName = messageBody["messageId"] as? String,
           let function = WmcFeedbackMessageId(rawValue: funcName)
        {
            // 携带的参数，不知道是啥
            let parameter = messageBody["messageData"]
            switch function {
            case .back:
                // 返回
                self.popVC()
            case .saveQrCode:
                // 保存二维码
                if let urlStr = parameter as? String,
                   let url = URL(string: urlStr)
                {
                    // 相册权限判断
                    let photoAlbumStatus = WmcAuthorizedManager.photoAlbum()
                    if photoAlbumStatus.info.isAvailable {
                        WmcHudManager.loading()
                        // kingFisher 下载图片
                        ImageDownloader.default.downloadImage(with: url, options: nil, completionHandler: { result in
                            WmcHudManager.dismiss()
                            if let imageData = try? result.get().originalData, let image = UIImage(data: imageData) {
                                // 保存图片到本地相册
                                UIImageWriteToSavedPhotosAlbum(image, self, #selector(self.saveImage(_:didFinishSaving:contextInfo:)), nil)
                            }
                        })
                    } else {
                        // 去设置权限
                        WmcAuthorizedManager.handleAlbumAuthorizationNotAvailable()
                    }
                }
            }
        }
    }
}

// MARK: - WKNavigationDelegate

extension WmcHtml5VC: WKNavigationDelegate {
    /// 决定是否允许加载
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        debugPrint("webview decidePolicyFor navigationAction")
        decisionHandler(.allow)
    }

    /// 开始加载时
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        debugPrint("webview didStartProvisionalNavigation")
        // placeholderView.isHidden = true
        WmcHudManager.loading()
    }

    /// 加载完成
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        debugPrint("webview didFinish navigation")
        WmcHudManager.dismiss()
    }

    /// 加载失败
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        debugPrint("webview didFail navigation")
        self.popVC()
        if !WmcLoginManager.shared.isLogin {
            WmcHudManager.toast("登录失效，请重新登录~")
        }
        WmcHudManager.dismiss()
    }

    /// 加载失败
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        debugPrint("webview didFailProvisionalNavigation navigation")
        self.popVC()
        if !WmcLoginManager.shared.isLogin {
            WmcHudManager.toast("登录失效，请重新登录~")
        }
    }
}
